package com.xuwang.Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xuwang.Util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @ Author  460503919
 * @ Date    2021/8/16 20:49
 * @ VERSION 1.0.0
 */
public class sendValidCode {

    /**
     * 发送成功则返回验证码，发送失败则返回 0
     * @param phone
     * @return int
     * @throws Exception
     */
    public int getMsg(String phone) throws Exception {
        //手机号
        phone = "+86" + phone;

        //获取验证码
        int code = (int) ((Math.random() * 9 + 1) * 1000);
        String host = "https://intlsms.market.alicloudapi.com";
        String path = "/comms/sms/sendmsgall";
        String method = "POST";
        String appcode = "e566ce8cb7474b8eaba607680d1997b0";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("callbackUrl", "http://test.dev.esandcloud.com");
        bodys.put("channel", "0");
        bodys.put("mobile", phone);
        bodys.put("templateID", "0000000");
        bodys.put("templateParamSet", "" + code + ", 1");
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
        String s = EntityUtils.toString(response.getEntity());
        JSONObject json = JSON.parseObject(s);
        if ("0000".equals(json.getString("code"))) {
            return  code;
        } else {
            return 0;
        }

    }
}
